﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using EQT.Dal;
using EQT.Model;
using System.Collections.Generic;

public partial class TaskDetailV2 : System.Web.UI.Page
{



    // 1大电流 2大电容
    private static readonly Common.Logging.ILog log = Common.Logging.LogManager.GetCurrentClassLogger();
    private DaContractTask dalTask = DevFuture.Common.WorkContext.AppCtx.GetObject("DaContractTask") as DaContractTask;
    private DaTuser dalUser = DevFuture.Common.WorkContext.AppCtx.GetObject("DaTuser") as DaTuser;
    private DaTfiles dalFiles = DevFuture.Common.WorkContext.AppCtx.GetObject("DaTfiles") as DaTfiles;
    private UserContext context;
    private string strHeaderUID = "";//组长角色编号，只有该角色可以下发任务、组长确认
    private string strDDL_GroupID = "TesterGroup_DDL";//大电流组ID，用来检索所有当前组里的用户。
    private string strDDR_GroupID = "TesterGroup_QDL";//大电容组ID，用来检索所有当前组里的用户。

    protected void Page_Load(object sender, EventArgs e)
    {
        context = Session["USER_CONTEXT"] as UserContext;
        OperationResult.Text = "";
        divResult.Visible = false;
        if (!IsPostBack)
        {
            btnAssign.Visible = false;
            btnStartTask.Visible = false;
            btnComplete.Visible = false;

            string strctid = Request.QueryString["CTID"];
            if (string.IsNullOrEmpty(strctid))
            {
                Response.End();
            }
            else
            {
                //数据权限检查 CTID 不一定是这个用户的

                ViewState["CTID"] = strctid;

                //根据状态设置UI
                MoContractTask moct = new MoContractTask();
                moct.CtId = strctid;
                if (dalTask.GetEntityEx(ref moct))
                {
                    if (moct.CtType == "1")
                    {
                        ViewState["strHeaderUID"] = "DDL_Master";
                    }
                    else
                    {
                        ViewState["strHeaderUID"] = "QDL_Master";
                    }

                    //主管实验员和实验员可能还未分配，可能为空值，防止异常，将为空时的编号赋一个永远不可能存在的字符串。
                    ViewState["Leader"] =string.IsNullOrEmpty( moct.CtLeaderId) ? "主管实验员" : moct.CtLeaderId;//主管实验员
                    ViewState["Tester"] =string.IsNullOrEmpty( moct.CtTesterId) ? "实验员" : moct.CtTesterId;//实验员
                    //ViewState["Leader"] = moct.CtLeaderId;//主管实验员
                    //ViewState["Tester"] = moct.CtTesterId;//实验员
                    ViewState["CtType"] = moct.CtType;    //任务类别
                    SetUIByTaskState(moct);
                }
                strHeaderUID = ViewState["strHeaderUID"].ToString();
                this.MakeView(strctid);
                SetUIByRights();
            }
        }
        strHeaderUID = ViewState["strHeaderUID"].ToString();
    }

    /// <summary>
    /// 任务下发
    /// </summary>
    protected void btnAssign_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(ddlTester.SelectedValue))
        {
            OperationResult.Text = "请选择主管实验员！"; divResult.Visible = true; return;
        }

        try
        {
            if (dalTask.TaskAssign(ViewState["CTID"].ToString(), context.UserID, ddlTester.SelectedValue))
            {
                OperationResult.Text = "任务下发成功！"; divResult.Visible = true;
            }
            else
            {
                OperationResult.Text = "任务下发失败！"; divResult.Visible = true; return;
            }
        }
        catch (Exception ex)
        {
            log.Error(ex);
            OperationResult.Text = "任务下发失败！"; divResult.Visible = true; return;
        }
        this.MakeView(ViewState["CTID"].ToString());
    }

    /// <summary>
    /// 开始执行
    /// </summary>
    protected void btnStartTask_Click(object sender, EventArgs e)
    {
        try
        {
            if (dalTask.TaskStart(ViewState["CTID"].ToString()))
            {
                OperationResult.Text = "任务已开始执行！"; divResult.Visible = true;
            }
            else
            {
                OperationResult.Text = "任务执行失败！"; divResult.Visible = true; return;
            }
        }
        catch (Exception ex)
        {
            log.Error(ex);
            OperationResult.Text = "任务执行失败！"; divResult.Visible = true; return;
        }
        this.MakeView(ViewState["CTID"].ToString());
    }

    /// <summary>
    /// 实验员确认
    /// </summary>
    protected void btnComplete_Click(object sender, EventArgs e)
    {
        try
        {
            if (dalTask.TaskComplete(ViewState["CTID"].ToString()))
            {
                OperationResult.Text = "确认成功！"; divResult.Visible = true;
            }
            else
            {
                OperationResult.Text = "确认失败！请检查检测结果记录文件是否上传！"; divResult.Visible = true; return;
            }
        }
        catch (Exception ex)
        {
            log.Error(ex);
            OperationResult.Text = "确认失败！"; divResult.Visible = true; return;
        }
        this.MakeView(ViewState["CTID"].ToString());
    }

    /// <summary>
    /// 组长确认
    /// </summary>
    protected void btnLeaderConfirm_Click(object sender, EventArgs e)
    {
        try
        {
            if (dalTask.TaskLeaderConfirm(ViewState["CTID"].ToString(), ViewState["REPORTID"].ToString()))
            {
                OperationResult.Text = "确认成功！"; divResult.Visible = true;
            }
            else
            {
                OperationResult.Text = "确认失败请检查检验结果记录文件是否已上传！"; divResult.Visible = true; return;
            }
        }
        catch (Exception ex)
        {
            log.Error(ex);
            OperationResult.Text = "确认失败！"; divResult.Visible = true; return;
        }
        this.MakeView(ViewState["CTID"].ToString());
    }

    /// <summary>
    /// 任务退回
    /// </summary>
    protected void btnReturnTask_Click(object sender, EventArgs e)
    {
        try
        {
            if (dalTask.TaskReturn(ViewState["CTID"].ToString()))
            {
                OperationResult.Text = "任务已退回！"; divResult.Visible = true;
            }
            else
            {
                OperationResult.Text = "任务退回失败！"; divResult.Visible = true; return;
            }
        }
        catch (Exception ex)
        {
            log.Error(ex);
            OperationResult.Text = "任务退回失败！"; divResult.Visible = true; return;
        }
        this.MakeView(ViewState["CTID"].ToString());
    }

    /// <summary>
    /// 确认按钮，返回到任务查询页面
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button_OK_Click(object sender, EventArgs e)
    {
        //返回到合同查询UI
        Response.Redirect("TaskListV2.aspx");
    }

    /// <summary>
    /// 绑定数据到界面中
    /// </summary>
    /// <param name="strctid">任务编号</param>
    protected void MakeView(string strctid)
    {
        DataSet ds = dalTask.GetOneTask(strctid);
        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            DataRow dr = ds.Tables[0].Rows[0];

            labAssignDate.Text = dr["CT_Assign_Date"].ToString();
            labBegindate.Text = dr["CT_Begin_Date"].ToString();
            labCTID.Text = dr["CT_ID"].ToString();
            labCtType.Text = dr["CT_TypeName"].ToString();
            labEndDate.Text = dr["CT_End_Date"].ToString();
            labLeader.Text = dr["LeaderName"].ToString();
            labPModel.Text = dr["PModel"].ToString();
            labPName.Text = dr["PName"].ToString();
            labPType.Text = dr["PType"].ToString();
            labReportID.Text = dr["Report_ID"].ToString();
            labReportID.Attributes.Remove("onclick");
            labReportID.Attributes.Add("onclick", "javascript:DisplayContract('" + dr["Report_ID"].ToString() + "');");

            labStatus.Text = dr["CT_StatusName"].ToString();
            labTester.Text = dr["TesterName"].ToString();
            ViewState["REPORTID"] = dr["Report_ID"].ToString();

            this.ConfigUpload(dr["CT_ID"].ToString(), int.Parse(dr["CT_Status"].ToString()), dr["CT_Type"].ToString(), dr["FID_DDL_Xls"].ToString(), dr["FID_DRL_Xls"].ToString());

            this.ConfigButtons(dr["CT_Status"].ToString(), dr["CT_Tester_id"].ToString(), dr["Report_ID"].ToString(), dr["CT_Type"].ToString());
        }
    }

    /// <summary>
    /// 根据状态和类型，以及文件上传情况，判断上传、下载按钮的可见性。
    /// </summary>
    /// <param name="intStatus"></param>
    /// <param name="strType"></param>
    /// <param name="strDdlFileid"></param>
    /// <param name="strDrlFileid"></param>
    private void ConfigUpload(string strCtid, int intStatus, string strType, string strDdlFileid, string strDrlFileid)
    {
        this.InitUploadControl(strCtid, strType);
        this.InitAttachmentUploadControl(strCtid, intStatus);
        labCheckFile.Text = GetFileName(strType == "1" ? strDdlFileid : strDrlFileid);
        labCheckFile.NavigateUrl = "getfile.aspx?fileid=" + (strType == "1" ? strDdlFileid : strDrlFileid);

        if (strType == "1")//大电流
        {
            if (strDdlFileid == "")//没上传
            {
                if (intStatus <= (int)CoTestItemStatus.Assigned)
                {
                    DisplayUploadFile(4);
                }
                else
                {
                    DisplayUploadFile(1);
                }
            }
            else
            {
                if (intStatus == (int)CoTestItemStatus.TaskDone)
                {
                    DisplayUploadFile(3);//组长确认后，不能删除。
                }
                else
                {
                    DisplayUploadFile(2);
                }
            }
        }
        else//大容量
        {
            if (strDrlFileid == "")//没上传
            {
                if (intStatus <= (int)CoTestItemStatus.Assigned)
                {
                    DisplayUploadFile(4);
                }
                else
                {
                    DisplayUploadFile(1);
                }
            }
            else
            {
                if (intStatus == (int)CoTestItemStatus.TaskDone)
                {
                    DisplayUploadFile(3);//组长确认后，不能删除。
                }
                else
                {
                    DisplayUploadFile(2);
                }
            }
        }

        //这里加一个判断，在上面的状态检测基础上，再对用户权限进行判断，只有组长和主管实验员，实验员有权限删除。
        if (btnDeleteFile.Visible)
        {
            if ((context.UserRole.RoleId == strHeaderUID) || (context.UserID == ViewState["Leader"].ToString()) || (context.UserID == ViewState["Tester"].ToString()))
            {
                btnDeleteFile.Visible = true;
            }
            else
            {
                btnDeleteFile.Visible = false;
            }
        }


        if ((intStatus == (int)CoTestItemStatus.None) || (intStatus == (int)CoTestItemStatus.Untread))
        {
            ddlTester.Visible = true;
            Utility.BindDataSet2Combox(dalUser.GetAllAvailableUsers(strType == "1" ? strDDL_GroupID : strDDR_GroupID), ddlTester, "Display_Name", "UID");

            //这里在列表中增加组长，任务可以下发给组长。
            DataSet dsMaster = dalUser.GetAllAvailableUsers(strType == "1" ? "DDL_Master" : "QDL_Master");
            for (int i = 0; i < dsMaster.Tables[0].Rows.Count; i++)
            {
                ddlTester.Items.Insert(0, new ListItem(dsMaster.Tables[0].Rows[i]["Display_Name"].ToString(), dsMaster.Tables[0].Rows[i]["UID"].ToString()));
            }

            ddlTester.Items.Insert(0, new ListItem("请选择主管实验员", ""));
            labTester.Visible = false;
        }
        else
        {
            ddlTester.Visible = false;
            labTester.Visible = true;
        }
    }

    private void InitUploadControl(string strCtid, string strType)
    {
        if ((context.UserRole.RoleId == strHeaderUID) || (context.UserID == ViewState["Leader"].ToString()) || (context.UserID == ViewState["Tester"].ToString()))
        {
            btnClientUpload.Visible = true;
            btnClientUpload.Text = "<input id='btnUploadFile' type='button' value='上传检测结果文件'onclick='javascript:InvokePopUploadParFile(\"" + strCtid + "\",\"" + strType + "\");' />";
        }
        else
        {
            btnClientUpload.Visible = false;
        }
    }

    private void InitAttachmentUploadControl(string strCtid, int intstatus)
    {
        btnOtherAttachment.Visible = false;
        RepFile.Visible = false;
        RepFileCanDel.Visible = false;


        if (intstatus == (int)CoTestItemStatus.Testing)
        {

            //主管试验员和组长,和实验员外不能删除附件文件。
            if ((context.UserRole.RoleId == strHeaderUID) || (context.UserID == ViewState["Leader"].ToString()) || (context.UserID == ViewState["Tester"].ToString()))
            {
                btnOtherAttachment.Visible = true;
                btnOtherAttachment.Text = "<input id='btnAttachmentUploadFile' type='button' value='上传检测附件文件'onclick='javascript:InvokePopUploadAttachment(\"" + strCtid + "\");' />";
                BindOtherAttachment(RepFileCanDel, strCtid);
            }
            else
            {
                btnOtherAttachment.Visible = false;
                BindOtherAttachment(RepFile, strCtid);
            }

        }
        else if (intstatus == (int)CoTestItemStatus.TestDone)
        {
            //主管试验员和组长,和实验员外不能删除附件文件。
            if ((context.UserRole.RoleId == strHeaderUID) || (context.UserID == ViewState["Leader"].ToString()) || (context.UserID == ViewState["Tester"].ToString()))
            {

                BindOtherAttachment(RepFileCanDel, strCtid);
            }
            else
            {
                BindOtherAttachment(RepFile, strCtid);
            }
        }
        else
        {
            BindOtherAttachment(RepFile, strCtid);
        }
    }


    protected void RepFileCanDel_OnItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            if (e.CommandName == "del")
            {
                dalFiles.DeleteOneAttachFile(e.CommandArgument.ToString());
                btnRefresh_Click(null, null);
            }
        }
    }

    private void BindOtherAttachment(Repeater rep, string strCtid)
    {
        rep.Visible = true;
        rep.DataSource = dalFiles.QueryFileRelation(strCtid + "_0");//这里是个Hack，表示是其他附件，与参数文件附件区分。
        rep.DataBind();
    }

    private string GetFileName(string fileid)
    {
        IList<MoTfiles> files = dalFiles.GetEntities(" where file_id='" + fileid + "'");
        if (files.Count > 0)
        {
            return files[0].FileName;
        }
        else
        {
            return "";
        }
    }

    /// <summary>
    /// 根据不同的状态设置按钮的可见性。
    /// </summary>
    /// <param name="strStatus">状态码</param>
    /// <param name="strTester">主管实验员编号</param>
    /// <param name="strReportID">合同编号</param>
    /// <param name="strType">合同类型</param>
    private void ConfigButtons(string strStatus, string strTester, string strReportID, string strType)
    {
        switch (int.Parse(strStatus))
        {
            case (int)CoTestItemStatus.None://已创建
                btnAssign.Visible = context.UserRole.RoleId == strHeaderUID ? true : false;
                btnStartTask.Visible = false;
                btnComplete.Visible = false;
                btnLeaderConfirm.Visible = false;
                btnReturnTask.Visible = false;
                break;
            case (int)CoTestItemStatus.Assigned://任务已下发
                btnAssign.Visible = false;
                btnStartTask.Visible = strTester == context.UserID ? true : false;
                btnComplete.Visible = false;
                btnLeaderConfirm.Visible = false;
                btnReturnTask.Visible = false;
                break;
            case (int)CoTestItemStatus.Testing://已开始
                btnAssign.Visible = false;
                btnStartTask.Visible = false;
                //btnComplete.Visible = strTester==context.UserID  ? true : false;
                //如果结果文件没上传，不允许完成实验。
                btnComplete.Visible = (strTester == context.UserID) && (dalTask.CheckResultFileIsCompleted(strReportID, int.Parse(strType)) == true) ? true : false;
                btnLeaderConfirm.Visible = false;
                btnReturnTask.Visible = false;
                break;
            case (int)CoTestItemStatus.TestDone://实验已完成
                btnAssign.Visible = false;
                btnStartTask.Visible = false;
                btnComplete.Visible = false;
                //btnLeaderConfirm.Visible = context.UserRole.RoleId == strHeaderUID ? true : false;
                //如果结果文件未上传，不允许确认。
                btnLeaderConfirm.Visible = (context.UserRole.RoleId == strHeaderUID) && (dalTask.CheckResultFileIsCompleted(strReportID, int.Parse(strType)) == true) ? true : false;
                btnReturnTask.Visible = context.UserRole.RoleId == strHeaderUID ? true : false;
                break;
            case (int)CoTestItemStatus.TaskDone://组长确认已完成
                btnAssign.Visible = false;
                btnStartTask.Visible = false;
                btnComplete.Visible = false;
                btnLeaderConfirm.Visible = false;
                btnReturnTask.Visible = false;
                break;
            case (int)CoTestItemStatus.Untread://组长退回
                btnAssign.Visible = context.UserRole.RoleId == strHeaderUID ? true : false;
                btnStartTask.Visible = false;
                btnComplete.Visible = false;
                btnLeaderConfirm.Visible = false;
                btnReturnTask.Visible = false;
                break;
            default:
                Utility.SiteError("任务状态字段值有异常！");
                return;
        }
    }

    /// <summary>
    /// 删除检测结果记录文件。
    /// </summary>
    protected void btnDeleteFile_Click(object sender, ImageClickEventArgs e)
    {
        DataSet ds = dalTask.GetOneTask(ViewState["CTID"].ToString());
        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            DataRow dr = ds.Tables[0].Rows[0];

            try
            {
                if (dalTask.RemoveAttath(dr["Report_ID"].ToString(), dr["CT_Type"].ToString()))
                {
                    OperationResult.Text = "删除监测记录文件成功！"; divResult.Visible = true; btnRefresh_Click(null, null); return;

                }
                else
                {
                    OperationResult.Text = "删除监测记录文件失败！"; divResult.Visible = true; return;
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                OperationResult.Text = "删除监测记录文件失败！"; divResult.Visible = true; return;
            }
        }
    }

    /// <summary>
    /// 删除检测结果对应的附件文件。
    /// </summary>
    protected void btnDeleteAttachment_Click(object sender, ImageClickEventArgs e)
    {
        //DataSet ds = dalTask.GetOneTask(ViewState["CTID"].ToString());
        //if (ds != null && ds.Tables[0].Rows.Count > 0)
        //{
        //    DataRow dr = ds.Tables[0].Rows[0];

        //    try
        //    {
        //        if (dalTask.RemoveAttath(dr["Report_ID"].ToString(), dr["CT_Type"].ToString()))
        //        {
        //            OperationResult.Text = "删除监测记录文件成功！"; divResult.Visible = true; btnRefresh_Click(null, null); return;

        //        }
        //        else
        //        {
        //            OperationResult.Text = "删除监测记录文件失败！"; divResult.Visible = true; return;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        log.Error(ex);
        //        OperationResult.Text = "删除监测记录文件失败！"; divResult.Visible = true; return;
        //    }
        //}
    }

    /// <summary>
    /// 设置上传部份的显示逻辑。1只显示上传按钮,2显示文件名和删除按钮,3只显示文件名 其他都不显示。
    /// </summary>
    /// <param name="flag">1只显示上传按钮,2显示文件名和删除按钮,3只显示文件名</param>
    private void DisplayUploadFile(int flag)
    {
        switch (flag)
        {
            case 1://只显示上传按钮
                btnClientUpload.Visible = true;
                labCheckFile.Visible = false;
                btnDeleteFile.Visible = false;
                break;
            case 2://显示文件名和删除按钮
                btnClientUpload.Visible = false;
                labCheckFile.Visible = true;
                btnDeleteFile.Visible = true;
                break;
            case 3://只显示文件名
                btnClientUpload.Visible = false;
                labCheckFile.Visible = true;
                btnDeleteFile.Visible = false;
                break;
            default:
                btnClientUpload.Visible = false;
                labCheckFile.Visible = false;
                btnDeleteFile.Visible = false;
                break;
        }
    }

    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(ViewState["CTID"].ToString()))
        {
            this.MakeView(ViewState["CTID"].ToString());
        }
    }


    #region 根据状态设置UI

    private void SetUIByTaskState(MoContractTask moct)
    {

        switch (moct.CtStatus)
        {
            case (int)CoTestItemStatus.Assigned://已下发
                {
                    btnAssign.Visible = false;
                    btnReturnTask.Visible = true;
                    btnLeaderConfirm.Visible = false;
                    btnStartTask.Visible = true;
                    btnComplete.Visible = false;
                    break;
                }
            case (int)CoTestItemStatus.Testing://测试中
                {
                    btnAssign.Visible = false;
                    btnReturnTask.Visible = true;
                    btnLeaderConfirm.Visible = false;
                    btnStartTask.Visible = false;
                    btnComplete.Visible = true;
                    break;
                }
            case (int)CoTestItemStatus.TestDone://测试完成
                {
                    btnAssign.Visible = false;
                    btnReturnTask.Visible = false;
                    btnLeaderConfirm.Visible = true;
                    btnStartTask.Visible = false;
                    btnComplete.Visible = false;
                    break;
                }
            case (int)CoTestItemStatus.TaskDone://组长确认测试完成
                {
                    btnAssign.Visible = false;
                    btnReturnTask.Visible = false;
                    btnLeaderConfirm.Visible = false;
                    btnStartTask.Visible = false;
                    btnComplete.Visible = false;
                    break;
                }
            case (int)CoTestItemStatus.Untread://被退回
                {
                    btnAssign.Visible = true;
                    btnReturnTask.Visible = false;
                    btnLeaderConfirm.Visible = false;
                    btnStartTask.Visible = false;
                    btnComplete.Visible = false;

                    break;
                }
        }
    }


    #endregion

    #region 权限检查
    /// <summary>
    /// 根据权限设置UI，仅在UI加载是执行一次.默认的，权限的ID都使用 对象名.资源名 。
    /// 如果资源必须与UI一同显示，则权限就是UI的名字。
    /// </summary>
    private void SetUIByRights()
    {
        /////下发任务
        //if (btnAssign.Visible)
        //{
        //    btnAssign.Visible = dalUser.CheckUserPrivilege(context.UserID, "TaskDetailV2.btnAssign");
        //}
        /////组长确认
        //if (btnLeaderConfirm.Visible)
        //{
        //    btnLeaderConfirm.Visible = dalUser.CheckUserPrivilege(context.UserID, "TaskDetailV2.btnLeaderConfirm");
        //}

        //这3个任务不检查，只检查UI一次即可。
        ///回退任务 只要能显示这个UI，则就可以操作此按钮
        //btnReturnTask.Visible = dalUser.CheckUserPrivilege(context.UserID, "TaskDetailV2");
        ///开始任务
        //btnStartTask.Visible = dalUser.CheckUserPrivilege(context.UserID, "TaskDetailV2");
        ///完成
        //btnComplete.Visible = dalUser.CheckUserPrivilege(context.UserID, "TaskDetailV2");       
    }


    #endregion

}
